<template>
    <div class="address-group">
        <slot name="title" />
        <el-row>
            <el-col :span="20">
                <base-table
                    :colunmData="addressTableHeader"
                    :tableData="channelReceiveInfoList"
                    :disabled="disabled"
                    :tableConfig="{
                        isMultiSelect: false,
                        isIndex: true,
                        highlightCurrentRow: false
                    }"
                    class="address-table"
                    @saveItem="saveItem"
                    @cancelItem="cancelItem"
                    @deleteItem="deleteItem"
                    @editItem="editItem"
                >
                    <template v-slot:tableCell="{ scope: { row, item } }">
                        <template v-if="['input', 'number'].includes(item.type) && row.edit">
                            <el-input
                                v-model="row[item.value]"
                                size="small"
                                class="select-input no-border-input"
                                :placeholder="$t('form.placeholder.input', { msg: '' })"
                                clearable
                            />
                        </template>
                        <template v-else-if="item.value === 'nation'">
                            <base-select
                                :value.sync="row[item.value]"
                                :disabled="disabled || !row.edit"
                                :item="{
                                    options: row.nationOptions
                                }"
                                @selectChange="(value, current) => nationChange(value, current, row)"
                                @visibleChange="visibleNation($event, row)"
                            />
                        </template>
                        <template v-else-if="item.value === 'province'">
                            <template v-if="row.nation === '中国'">
                                <base-select
                                    :value.sync="row[item.value]"
                                    :disabled="disabled || !row.edit"
                                    :item="{
                                        options: row.provinceOptions
                                    }"
                                    @selectChange="(value, current) => provinceChange(value, current, row)"
                                    @visibleChange="visibleProvince($event, row)"
                                />
                            </template>
                            <template v-else>
                                <el-input
                                    v-model="row[item.value]"
                                    size="small"
                                    class="select-input no-border-input"
                                    :placeholder="
                                        $t('form.placeholder.input', {
                                            msg: ''
                                        })
                                    "
                                    clearable
                                />
                            </template>
                        </template>
                        <template v-else-if="item.value === 'city'">
                            <template v-if="row.nation === '中国'">
                                <base-select
                                    :value.sync="row[item.value]"
                                    :disabled="disabled || !row.edit"
                                    :item="{
                                        options: row.cityOptions
                                    }"
                                    @visibleChange="visibleCity($event, row)"
                                    @selectChange="(value, current) => cityChange(value, current, row)"
                                />
                            </template>
                            <template v-else>
                                <el-input
                                    v-model="row[item.value]"
                                    size="small"
                                    class="select-input no-border-input"
                                    :placeholder="
                                        $t('form.placeholder.input', {
                                            msg: ''
                                        })
                                    "
                                    clearable
                                />
                            </template>
                        </template>
                        <template v-else-if="item.value === 'county'">
                            <template v-if="row.nation === '中国'">
                                <base-select
                                    :value.sync="row[item.value]"
                                    :disabled="disabled || !row.edit"
                                    :item="{
                                        options: row.countyOptions
                                    }"
                                    @visibleChange="visibleCounty($event, row)"
                                    @selectChange="(value, current) => countyChange(value, current, row)"
                                />
                            </template>
                            <template v-else>
                                <el-input
                                    v-model="row[item.value]"
                                    size="small"
                                    class="select-input no-border-input"
                                    :placeholder="
                                        $t('form.placeholder.input', {
                                            msg: ''
                                        })
                                    "
                                    clearable
                                />
                            </template>
                        </template>
                        <template v-else-if="item.type === 'radio'">
                            <el-radio
                                v-model="selectRadio"
                                :label="row['defaultFlag']"
                                :disabled="!row.edit"
                                class="select-radio pdl-10"
                                @change="radioChange($event, row)"
                            />
                        </template>
                        <template v-else>
                            <span class="pdl-10">{{ row[item.value] }}</span>
                        </template>
                    </template>
                </base-table>
                <div class="add-box f12">
                    <el-button id="btn_t_d_blue" class="mgl-10" type="text" size="mini" :disabled="disabled" @click="addAdress">
                        +{{ $t('supplie.detail.addAdress') }}
                    </el-button>
                </div>
            </el-col>
        </el-row>
    </div>
</template>
<script lang="ts">
// import Vue from 'vue'
import Component, { mixins } from 'vue-class-component';
import { Prop, Watch } from 'vue-property-decorator';
import { tabsConfig } from '../configs';
import { deepCopy, transformFields } from '@/utils';
import vuexMixins from '@/mixins/vuex-modulel-mixins';
import ValidataStrage from '@/utils/vaildateStrage';
import { Options, TableHeaderConfig } from '@/typings';
import commonApi from '@/api/common-api';
@Component({
    name: 'channel-address',
    components: {
        baseTitle: () => import('@/components/base-title/index.vue'),
        baseTable: () => import('@/components/base-table/index.vue'),
        baseSelect: () => import('@/components/base-select/index.vue')
    }
})
export default class App extends mixins(vuexMixins) {
    @Prop({ default: false }) disabled: boolean;
    @Prop({ required: true }) channelReceiveInfoList: any[];

    addressTableHeader = tabsConfig.address;
    selectRadio: boolean = true;

    // 拷贝一份数据
    deepTableData: any[] = [];
    nationOptions: Options[] = [];
    provinceOptions: Options[] = [];
    cityOptions: Options[] = [];
    countyOptions: Options[] = [];
    @Watch('v_status', { immediate: true })
    onv_statusChange(val) {
        if (['add', 'edit', 'cancel'].includes(val)) {
            this.deepTableData = deepCopy(this.channelReceiveInfoList);
        }
    }

    async getAreaListByParentId(parentName, row, areaType) {
        const res = await this._get({
            url: `${commonApi.getAreaListByParentId}`,
            params: {
                columnName: areaType,
                parentName
            }
        });
        if (res.code === 0) {
            this.$set(
                row,
                `${areaType}Options`,
                transformFields(res.data, {
                    label: 'name',
                    value: 'name',
                    realValue: 'id'
                })
            );
        }
    }
    nationChange(value, current, row) {
        row.province = '';
        row.city = '';
        row.county = '';
        this.getAreaListByParentId(current.value, row, 'province');
    }
    provinceChange(value, current, row) {
        row.city = '';
        row.county = '';
        this.getAreaListByParentId(current.value, row, 'city');
    }
    cityChange(value, current, row) {
        row.county = '';
        this.getAreaListByParentId(current.value, row, 'county');
    }
    countyChange() {
        // this.getAreaListByParentId(0, 'nationOptions')
    }
    visibleNation(value, row) {
        // console.log('visibleNation obj', value, row)
        if (value && !row.nationOptions.length) {
            this.getAreaListByParentId('', row, 'nation');
        }
    }
    visibleProvince(value, row) {
        if (value && !row.provinceOptions.length && row.nation) {
            this.getAreaListByParentId(row.nation, row, 'province');
        }
    }
    visibleCity(value, row) {
        if (value && !row.cityOptions.length && row.province) {
            this.getAreaListByParentId(row.province, row, 'city');
        }
    }
    visibleCounty(value, row) {
        if (value && !row.countyOptions.length && row.city) {
            this.getAreaListByParentId(row.city, row, 'county');
        }
    }
    editItem({ row }) {
        this.$set(row, 'edit', true);
    }

    deleteItem({ $index }) {
        this.channelReceiveInfoList.splice($index, 1);
        this.deepTableData.splice($index, 1);
    }
    validate(row): boolean | void {
        const requiredArr: Pick<TableHeaderConfig, 'value' | 'label' | 'lang'>[] = [];
        this.addressTableHeader.forEach((item) => {
            if (item.require)
                requiredArr.push({
                    value: item.value,
                    label: item.label,
                    lang: item.lang
                });
        });
        const obj = requiredArr.find((item) => {
            return !row[item.value];
        });
        if (obj) {
            this._message({
                message: this.$t('form.placeholder.input', {
                    msg: this.$t(obj.lang!)
                }),
                type: 'error'
            });
            return true;
        }
    }
    saveItem({ row, $index }) {
        const validate = new ValidataStrage();
        const validateMsg = validate.changeState('isMobile').goes({ isMobile: { value: row.mobile } });
        if (validateMsg) {
            // this._message({ message: '请输入编码', type: 'error' })
            this._message({ message: validateMsg, type: 'error' });
            return;
        }
        if (this.validate(row)) return;
        this.$set(row, 'edit', false);
        this.$set(this.deepTableData, $index, Object.assign({}, row));
    }
    cancelItem({ row, $index }) {
        if (!row.id) {
            this.channelReceiveInfoList.splice($index, 1);
            this.deepTableData.splice($index, 1);
        } else {
            this.$set(this.channelReceiveInfoList, $index, Object.assign({}, this.deepTableData[$index]));
            this.$set(row, 'edit', false);
        }
    }
    // 单选框
    radioChange(val, row) {
        this.channelReceiveInfoList.forEach((item) => {
            item.defaultFlag = false;
        });
        row.defaultFlag = true;
        this.selectRadio = true;
    }

    addAdress() {
        this.channelReceiveInfoList.push({
            edit: true,
            defaultFlag: 0,
            nation: '',
            province: '',
            city: '',
            county: '',
            address: '',
            contactsPerson: '',
            postCode: '',
            mobile: '',
            provinceOptions: [],
            cityOptions: [],
            countyOptions: [],
            nationOptions: []
        });
    }
}
</script>

<style lang="scss" scoped>
@import 'src/styles/variables.scss';
.address-table {
    /deep/.cell {
        padding: 0 !important;
    }
}
.add-box {
    color: $colorTextRegular;
    height: 28px;
    line-height: 28px;
    border: 1px solid #eee;
    border-top: none;
    &-text {
        width: 50px;
        display: inline-block;
        padding-left: 10px;
        border-right: 1px solid #eee;
    }
    .inline-block {
        display: inline-block;
        width: 200px;
        padding-left: 10px;
        color: $basic;
        &:hover {
            cursor: pointer;
        }
    }
}
/deep/.select-radio .el-radio__label {
    display: none;
}
</style>
